import wx from '../../subwe/bridge';
import WXComponent from "../../subwe/component";
import { Index } from '../../apis/index';
const app = getApp();
const API = new Index();
WXComponent({
  properties: {
    limit: {
      type: Number,
      //类型
      value: 99
    },
    count: {
      type: Number,
      value: 9
    }
  },
  data: {
    imageUrl: `${app.globalData.imageUrl}/zhongman2`,
    uploadList: []
  },
  methods: {
    // 删除图片
    deleteImg(e) {
      const index = Number(e.currentTarget.dataset.index);
      const list = this.data.uploadList.filter((i, key) => index !== key);
      this.setData({
        uploadList: list
      });
      this.triggerEvent('updateImg', list);
    },
    // 图片上传
    uploadClick() {
      let list = this.data.uploadList;
      const _this = this;
      const token = wx.getStorageSync('login_key').token;
      const {
        count,
        limit
      } = this.properties;
      wx.chooseImage({
        count,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          res.tempFilePaths.map((i, index) => {
            wx.uploadFile({
              url: app.globalData.apiUrl + "upload-img",
              filePath: i,
              name: 'file',
              header: {
                'content-type': 'multipart/form-data',
                'Access-Token': `dingo ${token}`
              },
              success(res) {
                console.log("res", res);
                const {
                  fileName,
                  host,
                  hostPath
                } = JSON.parse(res.data).result;
                if (limit < list.length + 1) {
                  wx.showToast({
                    title: `最多上传${limit}张图片`,
                    icon: 'none'
                  });
                  return;
                }
                list.push(host + hostPath + fileName);
                _this.setData({
                  uploadList: list
                });
                _this.triggerEvent('updateImg', list);
              },
              fail(res) {
                console.log("fail===>", res);
              }
            });
          });
        },
        fail(res) {
          console.log("fail===>", res);
        }
      });
    }
  }
});